package com.yuufa.test.ex;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class Ex6 {
    
    public static void main(String[] args) throws Exception {
        
        // get user input from console
        // BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        
    }
    
    public static void test1(String[] args) throws Exception {

        readtxt(new File("d:\\test.txt"), 'i'); // i 出現次數
        readtxt(new File("d:\\test.txt"), "to"); // if 出現次數
    }
    
    // yuufa
    public static int count(char[] source, char[] target) {

        int count = 0;
        char first = target[0];
        int slen = source.length;
        int tlen = target.length;
        int max = slen - tlen;

        for (int i = 0; i <= max; i++) {
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            if (i <= max) {
                int j = i + 1;
                int end = i + tlen - 1;

                for (int k = 1; j <= end && source[j] == target[k]; k++, j++);

                if (j == (end + 1)) {
                    count++;
                }
            }
        }

        return count;
    }
    
    public static void readtxt(File file, String key) throws Exception {
        
        BufferedReader br = new BufferedReader(new FileReader(file)); // yuufa
        
        String line = null;
        int count = 0;
        
        // yuufa
        while( (line = br.readLine()) != null ) {
            count += count(line.toCharArray(), key.toCharArray());
        }
        
        System.out.println(count);
    }
    
    public static void readtxt(File file, char key) throws Exception {
        
        BufferedReader br = new BufferedReader(new FileReader(file));
        
        int read = 0;
        int count = 0;
        
        // yuufa
        while( (read = br.read()) != -1 ) {
            if( (char) read == key ) {
                count++;
            }
        }
        
        System.out.println(count);
    }

    public static void test(String[] args) {

        int n = 4;
        int[] s = {0, 45, 68, 77, 33};
        print(s, n);
    }

    public static void print(int[] s, int n) {

        int[][] r = new int[n + 1][n + 1];

        for (int i = 1; i <= n; i++) {
            r[n][i] = s[i];
        }

        for (int row = n - 1; row >= 1; row--) {
            for (int i = 1; i <= row; i++) {
                r[row][i] = Math.abs( r[row+1][i]-r[row+1][i+1] );
            }
        }
        
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=n-i;j++) {
                System.out.printf("%2s","");
            }
            for(int j=1;j<=i;j++) {
                System.out.printf("%4d",r[i][j]);
            }
            System.out.println();
        }
    }
}
